package com.qingcloud.adminbackend.controller;

import com.google.common.collect.ImmutableMap;
import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.entity.common.CascadeTree;
import com.qingcloud.adminbackend.entity.domain.DomainSelectDTO;
import com.qingcloud.adminbackend.entity.domain.SysDomain;
import com.qingcloud.adminbackend.service.ISysDomainService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 区域信息controller
 */
@Api(value = "区域信息API", description = "区域信息API")
@RestController
@RequestMapping("/domain")
public class SysDomainController {

    @Resource
    private ISysDomainService sysDomainService;

    @ApiOperation(value = "查询所有省", notes = "查询所有省", response = SysDomain.class)
    @GetMapping(value = "/province")
    public AjaxResult province(HttpServletRequest request) {
        return new AjaxResult(WamingConstant.SUCCESS, "", sysDomainService.getAllProvince());
    }

    @ApiOperation(value = "根据父ID查询子区域", notes = "根据父ID查询子区域", response = SysDomain.class)
    @ApiImplicitParams(
            @ApiImplicitParam(name = "parentId", value = "parentId",
                    required = true, dataType = "int", paramType = "path", defaultValue = "370800")
    )
    @GetMapping(value = "/child/{parentId}")
    public AjaxResult child(HttpServletRequest request, @PathVariable("parentId") Integer parentId) {
        return new AjaxResult(WamingConstant.SUCCESS, "", sysDomainService.listByMap(ImmutableMap.of("parent_id", parentId)));
    }

    @ApiOperation(value = "区域级联选择空间专用", notes = "区域级联选择空间专用", response = SysDomain.class)
    @GetMapping(value = "/picker")
    public AjaxResult picker() {
        //查询出所有区域
        List<SysDomain> allList = sysDomainService.list(null);
        //过滤出所有省
        List<SysDomain> provinceList = allList.stream().filter(it -> "1".equals(it.getCityType())).collect(Collectors.toList());
        //省按首字母分组
        Map<String, List<SysDomain>> pinyinMap = provinceList.stream().collect(Collectors.groupingBy(SysDomain::getFirstPinyin));
        //最终结果hash表
        Map<String, Object> resultMap = new HashMap<>();
        //首字母分组结果
        Map<String, List<DomainSelectDTO>> firstMap = new LinkedHashMap<>();
        List<DomainSelectDTO> agList = new ArrayList<>();
        List<DomainSelectDTO> hkList = new ArrayList<>();
        List<DomainSelectDTO> lsList = new ArrayList<>();
        List<DomainSelectDTO> tzList = new ArrayList<>();
        pinyinMap.keySet().forEach(pinyin -> {
            //取出返回对象
            List<DomainSelectDTO> dtoList = pinyinMap.get(pinyin).stream()
                    .map(it -> new DomainSelectDTO(String.valueOf(it.getId()), it.getDomainName()))
                    .collect(Collectors.toList());
            //首字母判断
            char first = pinyin.toUpperCase().charAt(0);
            //A-G分组
            if (first >= 'A' && first <= 'G') {
                agList.addAll(dtoList);
            }
            //H-K分组
            if (first >= 'H' && first <= 'K') {
                hkList.addAll(dtoList);
            }
            //L-S分组
            if (first >= 'L' && first <= 'S') {
                lsList.addAll(dtoList);
            }
            //T-Z分组
            if (first >= 'T' && first <= 'Z') {
                tzList.addAll(dtoList);
            }
        });
        firstMap.put("A-G", agList);
        firstMap.put("H-K", hkList);
        firstMap.put("L-S", lsList);
        firstMap.put("T-Z", tzList);
        resultMap.put("86", firstMap);
        //非省列表
        List<SysDomain> domainList = allList.stream().filter(it -> !"1".equals(it.getCityType())).collect(Collectors.toList());
        //非省君安父ID分组
        Map<String, List<SysDomain>> domainMap = domainList.stream()
                .collect(Collectors.groupingBy(it -> String.valueOf(it.getParentId())));
        domainMap.keySet().forEach(pid -> {
            List<SysDomain> childList = domainMap.get(pid);
            Map<String, String> childMap = new HashMap<>(childList.size());
            childList.forEach(it -> childMap.put(String.valueOf(it.getId()), it.getDomainName()));
            resultMap.put(pid, childMap);
        });
        return new AjaxResult(WamingConstant.SUCCESS, "", resultMap);
    }

    @ApiOperation(value = "区域级联树", notes = "区域级联树")
    @GetMapping(value = "/cascade/tree")
    public AjaxResult<List<CascadeTree>> tree(HttpServletRequest request) {
        //查询出所有区域
        List<SysDomain> allList = sysDomainService.list(null);
        //转成树结构
        List<CascadeTree> treeList = allList.stream().map(it -> {
            Long parentId = it.getParentId();
            CascadeTree cascadeTree = new CascadeTree();
            if (Objects.isNull(parentId)) {
                cascadeTree.setParentValue(null);
            } else {
                cascadeTree.setParentValue(parentId.toString());
            }
            cascadeTree.setValue(String.valueOf(it.getId())).setLabel(it.getDomainName());
            return cascadeTree;
        }).collect(Collectors.toList());
        return new AjaxResult<>(WamingConstant.SUCCESS, "", CascadeTree.convertTree(treeList));
    }

}
